#第9章 异常
# print(a)

print('----------处理异常----------------')
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
def test_exception(x,y):
    try:
        a = x/y
        print('a=',a)
        return a
    except Exception:
        print('程序发生异常，被除数为0')

test_exception(10,0)

print('----------抛出异常----------------')
#raise Exception

#raise NameError('this is nameerror')

def test_exception2():
    try:
        raise NameError('This is a NameError')
    except NameError:
        print('发生异常！')
        #raise 如果只想知道是否抛出了异常，不想处理。加上raise语句把异常再次抛出


test_exception2()

print('----------抛出异常----------------')
def test_expcetion3(a,b):
    try:
        c = a / b
        #c = name
        return c
    except ZeroDivisionError:
        print('除数不能为0')
    except NameError:
        print('对象未声明')

test_exception(10,0)

print('----------抛出多个异常----------------')
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
def test_expceiton4(a,b):
    try:
        c = a/b
        return c
    except (ZeroDivisionError,NameError,TypeError):
        print('发生了异常！')

test_expceiton4(10,0)

print('----------捕捉对象----------------')
def test_expceiton5(a,b):
    try:
        c = a/b
        return c
    except (ZeroDivisionError,NameError,TypeError) as e:
        print(e)

test_expceiton5(10,0)

print('----------全捕获----------------')
def test_expceiton5(a,b):
    try:
        c = a/b
        return c
    except:
        print('全捕获异常')

test_expceiton5(10,'')

print('----------else----------------')
def test_expceiton6(a,b):
    try:
        c = a/b
    except:
        print('全捕获异常')
    else:
        print('没有发生异常')

test_expceiton6(10,5)

print('----------自定义异常----------------')
#! /usr/bin/python3
# -*- coding:UTF-8 -*-
# 自定义异常类最好以Error结尾，方便识别
class MyError(Exception):
    def __init__(self):
        pass

    def __str__(self):
        return 'this is my error'

def my_error_test():
    try:
        raise MyError()
    except MyError as e:
        print('exception e is:',e)

my_error_test()

print('----------finally----------------')
def use_finally(a,b):
    try:
        c = a/b
        print('c=',c)
    except Exception:
        print('发生异常')
    else:
        print('顺利上岸，没有发生异常')
    finally:
        print('不管是否发生异常，我都会出现！')

# use_finally(10,0)#测试发生异常
use_finally(10,5)#测试不发生异常

print('----------异常与函数----------------')
def divide_func(a,b):
    return a/b

def exec_divide_func(a,b):
    return divide_func(a,b)*10

def main(a,b):
    return exec_divide_func(a,b)

main(10,0)